package com.xagent.engine.hook.enhance.v1;

import com.xagent.core.GlobalEntry;
import com.xagent.engine.hook.MethodInfo;
import org.objectweb.asm.MethodVisitor;

/**
 * Author: 4ut15m
 * 通用hook
 */
public class CommonAdviceAdapter extends XagentMethodVisitor {
    private String className;
    private MethodInfo methodInfo;

    protected CommonAdviceAdapter(MethodVisitor methodVisitor, int access, String name, String descriptor, String className, MethodInfo methodInfo) {
        super(methodVisitor, access, name, descriptor);
        this.className = className;
        this.methodInfo = methodInfo;
    }

    @Override
    protected void onMethodEnter() {
        mark(beginLabel);
        loadThis();
        loadAllArgs();
        visitLdcInsn(methodInfo.getIndex());
        visitLdcInsn(className);
        visitLdcInsn(getName());
        visitLdcInsn(methodDesc);
        mv.visitMethodInsn(INVOKESTATIC, GlobalEntry.class.getName().replaceAll("\\.", "/"), "monitorMethodEnter", "(Ljava/lang/Object;[Ljava/lang/Object;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", false);
        super.onMethodEnter();
    }

    @Override
    protected void onMethodExit(int opcode) {
        if (!isThrow(opcode)) {
            loadReturn(opcode);
            loadThis();
            loadAllArgs();
            visitLdcInsn(methodInfo.getIndex());
            visitLdcInsn(className);
            visitLdcInsn(getName());
            visitLdcInsn(methodDesc);
            mv.visitMethodInsn(INVOKESTATIC, GlobalEntry.class.getName().replaceAll("\\.", "/"), "monitorMethodExit", "(Ljava/lang/Object;Ljava/lang/Object;[Ljava/lang/Object;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", false);
        }

        super.onMethodExit(opcode);
    }


}
